<?php
class Order{
    protected $main_table = 'data_order';
	protected $main_id = 'order_id';
	protected $main_id2 = 'order_sn';
	protected $db = null;
	
	public function __construct($db){
		$this->db=$db;
	}
   
	public function __destruct(){
		unset($this->db);
	}
	public function get_table_name(){
	    return $this->main_table;
	    
	}
	/**
	* 	insert order
	* 	@param array $data 
	* 	@return int affected count
	*/
	public function insert_data($data){
		if(!is_array($data))
		my_jump('输入的参数有误');
		$rows = $this->db->insert($this->main_table, $data);
		$insert_id = $this->db->getInsertId();
		return $insert_id;	
	}
	
	/**
	* 	update order
	* 	@param array $data 
	* 	@param string $where 
	* 	@return int affected count
	*/
	public function update_data($data,$where){
		if(!is_array($data))
		my_jump('输入的参数有误');
		$result = $this->db->update($this->main_table,$data,$where);
		return $result;
	}
	
	/**
	* 	delete order
	* 	@param string $where 
	* 	@return int affected count
	*/
	public function del_data($where){
		$result = $this->db->delete($this->main_table,$where);
		return $result;
	}	
	
	/**
	* 	get order info
	* 	@param int $id 
	*	@param array/string $field
	* 	@return array one row data
	*/
	public function get_data_row($id,$field='*',$where=''){
		if(!intval($id))
		my_jump('输入的参数有误!');
		$sql = "SELECT ".$field." FROM ".$this->main_table." WHERE ".$this->main_id."='".intval($id)."' ";
		if($where){
			$sql .= " AND ".$where;
		}

		$data = $this->db->getRow($sql);
		return $data;
	}	
	
	/**
	* 	get order array
	* 	@param string $where
	* 	@return array data
	*/
	public function get_data_array($where,$order='order_id DESC',$limit='10',$field='*'){
		$sql = "SELECT ".$field." FROM ".$this->main_table." WHERE ".$where." ORDER BY ".$order;
		if(intval($limit)){
			$sql .= " LIMIT ".$limit;
		}
		$data = $this->db->getAll($sql);
		return $data;
	}  
	
	public function get_row_by_sn($sn,$field='*'){
		if(!intval($sn))
		my_jump('输入的参数有误!');
		$sql = "SELECT ".$field." FROM ".$this->main_table." WHERE ".$this->main_id2."='".$sn."' ";
		$data = $this->db->getRow($sql);
		return $data;
	}
	
	public function get_alipay_page($info){
		require_once(CONFIG_PATH.'alipay_config.php');
		require_once(LIB_PATH.'alipay/alipay_submit.class.php');
		
		$return_url = $alipay_config['return_url'];			//返回地址
		$notify_url = $alipay_config['notify_url'];			//ajax返回地址,不能放在需要登录或验证的页面	

		$parameter = array(
					"service" => "create_direct_pay_by_user",					//*接口方式
					"partner" => $alipay_config['partner'],						//*alipay 合作身份者id，以2088开头的16位纯数字
					"payment_type"	=> '1',										//*支付类型
					"notify_url"	=> $notify_url,						//ajax返回通知页面路径 不能加?id=123这类自定义参数 
					"return_url"	=> $return_url,						//页面跳转同步通知页面路径
					"seller_email"	=> $alipay_config['seller_email'],				//*商家淘宝账号
					"out_trade_no"	=> $info['sn'],								//*商户唯一订单号
					"subject"	=> $info['title'],								//*订单名称
					"total_fee"	=> $info['money'],								//*支付金额
					"body"	=> $info['des'],									//订单描述
					"show_url"	=> '',											//商品展示地址
					"anti_phishing_key"	=> '',									//防钓鱼时间戳,若要使用请调用类文件submit中的query_timestamp函数
					"exter_invoke_ip" => '',									//客户端的IP地址,非局域网的外网IP地址，如：221.0.0.1
					"_input_charset" =>$alipay_config['input_charset']								//编码 utf-8
			);		
		//dump($parameter);
		//建立请求
		$alipaySubmit = new AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "前往支付");		
		
		//echo $html_text;
		return $html_text;

	}
	
	public function get_alipay_wap_page($info){
		require_once(CONFIG_PATH.'alipay_config.php');
		require_once(LIB_PATH.'alipay/alipay_submit.class.php');
		
		$return_url = $alipay_config['return_url'];			//返回地址
		$notify_url = $alipay_config['notify_url'];			//ajax返回地址,不能放在需要登录或验证的页面	

		$parameter = array(
					"service" => "alipay.wap.create.direct.pay.by.user",					//*接口方式
					"partner" => $alipay_config['partner'],						//*alipay 合作身份者id，以2088开头的16位纯数字
					"payment_type"	=> '1',										//*支付类型
					"notify_url"	=> $notify_url,						//ajax返回通知页面路径 不能加?id=123这类自定义参数 
					"return_url"	=> $return_url,						//页面跳转同步通知页面路径
					"seller_id"	=> $alipay_config['seller_email'],				//*商家淘宝账号
					"out_trade_no"	=> $info['sn'],								//*商户唯一订单号
					"subject"	=> $info['title'],								//*订单名称
					"total_fee"	=> $info['money'],								//*支付金额
					"body"	=> $info['des'],									//订单描述
					"show_url"	=> '',											//商品展示地址
					"anti_phishing_key"	=> '',									//防钓鱼时间戳,若要使用请调用类文件submit中的query_timestamp函数
					"exter_invoke_ip" => '',									//客户端的IP地址,非局域网的外网IP地址，如：221.0.0.1
					"_input_charset" =>$alipay_config['input_charset']								//编码 utf-8
			);		
		//dump($parameter);
		//建立请求
		$alipaySubmit = new AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "前往支付");		
		
		//echo $html_text;
		return $html_text;

	}
	
	public function return_verify(){
		require_once(CONFIG_PATH.'alipay_config.php');
		require_once(LIB_PATH.'alipay/alipay_notify.class.php');

		$alipay_notify = new AlipayNotify($alipay_config);
		$verify_result = $alipay_notify->verifyReturn();
	
		if($verify_result) {//验证成功			
			$out_trade_no = $_GET['out_trade_no'];			//商户订单号
			$trade_no = $_GET['trade_no'];					//支付宝交易号
			$trade_status = $_GET['trade_status'];			//交易状态			
		
			if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
				//更新订单状态,注意:状态可能在之前的ajax_verify已经提交
				//echo "支付成功<br />";
				return true;
			}
			else {
				//支付失败
				return false;		  
			}			
		}
		else {				
			return false;
			//如要调试，请看alipay_notify.php页面的verifyReturn函数
			//echo "验证失败";
		}
	}
	
	
	//支付宝,ajax返回信息,在不需要验证或登录的页面内
	public function ajax_verify(){
		require_once(CONFIG_PATH.'alipay_config.php');
		require_once(LIB_PATH.'alipay/alipay_notify.class.php');
		$alipay_notify = new AlipayNotify($alipay_config);
		$verify_result = $alipay_notify->verifyNotify();
		if($verify_result){
			$out_trade_no = $_POST['out_trade_no'];  //支付时提交的商品唯一订单号
			$trade_no = $_POST['trade_no'];				//支付宝系统中的交易流水号
			$trade_status = $_POST['trade_status'];		//结果状态
			if($trade_status=='TRADE_FINISHED' || $trade_status=='TRADE_SUCCESS'){
				return true;
				/*
				订单更新状态 事件记录
				*/	
				//echo "success";		//请不要修改或删除,返回给支付宝
			}else{
				// ajax接收结果失败
				//更新订单状态
			}
		}else{
			return false;
			//echo "fail";			//请不要修改或删除,返回给支付宝
		}
	}	
	
	function update_order2($info){
		$out_trade_no = $info['out_trade_no'];  //支付时提交的商品唯一订单号
		$trade_no = $info['trade_no'];				//支付宝系统中的交易流水号
		$trade_status = $info['trade_status'];		//结果状态
		$total_fee = $info['total_fee'];			//总费用
		$pay_from = $info['pay_from'];			//支付来源	
		$row = $this->get_row_by_sn($out_trade_no);		
		if($row){
			switch($row['order_status']){
			case "1":  //已支付不处理
				return true;
			break;
			default :	//更新订单状态
				if($total_fee!=$row['order_total']){			
									
					$update = array(
						'order_status'=>'1',
						'order_pay_from'=>$pay_from,						
						'order_pay_sn'=>$trade_no,
						'order_return_time'=>date("Y-m-d H:i:s"),						
						'order_return_status'=>$trade_status,
					);										
					$rs = $this->update_data($update,"order_id='".$row['order_id']."'");//更新订单信息														
					if($rs){					
						return true;						
						
					}else{									
						return false;						
					}					
				}			
			break;
			}
		}	
		
	}
	
	function update_order($info){		
		$out_trade_no = $info['out_trade_no'];  //支付时提交的商品唯一订单号
		$trade_no = $info['trade_no'];				//支付宝系统中的交易流水号
		$trade_status = $info['trade_status'];		//结果状态
		$total_fee = $info['total_fee'];			//总费用
		$pay_from = $info['pay_from'];			//支付来源			
		$row = $this->get_row_by_sn($out_trade_no);				
		if($row){
			switch($row['order_status']){
			case "1":  //已支付不处理
				return true;
			break;
			default :	//更新订单状态
				if($total_fee==$row['order_total']){
					$this->db->begin();//开始事物
					//搭伙购的发起人和开始时间的添加(只针对订单是搭伙购的订单)
					if($row['order_type'] && $row['order_gid']){
						//判断商品的最新搭伙购是否已经存在
						load_file('board_class',LIB_PATH);						
						$board = new Board($this->db);
						$today = date("Y-m-d");
						$where = "board_gid = '".$row['order_gid']."' AND board_end_time >= '".$today."'";
						$board_row = $board->get_row_by_where($where);						
						if($board_row){//如果存在搭伙购则更新搭伙购的信息
							$update = array(
										'board_sales'=>'board_sales+1',
									);
							$where = "board_id = '".$board_row['board_id']."'";		
							$rs = $board->update_data($update,$where);
							$board_id = $board_row['board_id'];		
							
						}else{//如果不存在搭伙购，则添加搭伙购
							load_file('goods_class',LIB_PATH);						
							$goods = new Goods($this->db);
							$goods_row = $goods->get_data_row($row['order_gid'],'goods_board_days');							
							$end_time = date("Y-m-d",strtotime("+".$goods_row['goods_board_days']." days"));
							$insert = array(
								'board_gid'=>$row['order_gid'],
								'board_uid'=>$row['order_uid'],
								'board_user'=>$row['order_user'],
								'board_sales'=>'1',
								'board_start_time'=>$today,
								'board_end_time'=>$end_time,
								'board_create_time'=>date("Y-m-d H:i:s")
							);
							$rs = $board->insert_data($insert);
							$board_id = $rs;							
						}
						
					}else{
						$rs = 1;
					}		
									
					$update = array(
						'order_status'=>'1',
						'order_pay_from'=>$pay_from,						
						'order_pay_sn'=>$trade_no,
						'order_return_time'=>date("Y-m-d H:i:s"),						
						'order_return_status'=>$trade_status,
					);
					//更新搭伙购的ID
					if($board_id){
						$update['order_boardid'] = $board_id;
					}															
					$rs2 = $this->update_data($update,"order_id='".$row['order_id']."'");//更新订单信息														
					
					//更新商品的用户购买信息
					$this->update_goods_user($row);
					if($rs && $rs2){						
						$this->send_controller_mail($row['order_sn']);//提示蔡鹏的发货邮件
						$this->db->commit();					
						return true;						
						
					}else{
						$this->db->back();									
						return false;						
					}					
				}			
			break;
			}
		}	
		
	}
	
	
	public function get_order_list($where,$field='*',$limit=''){	
		$sql = "SELECT ".$field." FROM data_order LEFT JOIN data_goods ON order_goods_id=goods_id WHERE $where order by order_id desc";
		if($limit){
			$sql .= " limit ".$limit;
		}
		$data = $this->db->getAll($sql);
		return $data;
	}	
	
	public function complete_order($id){
		$row = $this->get_data_row($id);
		if($row){
			load_file('sp_class',LIB_PATH);
			
			$this->db->begin();
			$sp = new Sp($this->db);
			
			$update['order_status'] = '3';
			$update['order_complete_time'] = date("Y-m-d H:i:s");	
			
			$rs1 = $this->update_data($update, "order_id = '$id'");
			if($row['order_spid1'] && $row['order_sp_rebate1']){
				 $update1 = array('sp_money'=>"sp_money+".$row['order_sp_rebate1'],'sp_sales'=>"sp_sales+".$row['order_total'],'sp_sales_order'=>"sp_sales_order+1");
				 $rs2 = $sp->update_data($update1,"sp_id='".$row['order_spid1']."'");
				 $sp_money_data = array(
					  'log_spid' => $row['order_spid1'],
					  'log_sp' => $row['order_sp1'],
					  'log_type' => 'order_rebate',
					  'log_money' => $row['order_sp_rebate1'],
					  'log_content' => "交易返利(SN:".$row['order_sn'].")",
					  'log_create_time' => date("Y-m-d H:i:s"),
					  'log_main_id' => $row['order_id'],
				  );
				$rs3 = $this->db->insert('data_sp_money_log', $sp_money_data); //商家资金记录	
			}else{
				$rs2 = '1';
				$rs3 = '1';
			}
			if($row['order_spid2'] && $row['order_sp_rebate2']){
				$update2 = array('sp_money'=>"sp_money+".$row['order_sp_rebate2'],'sp_sales_order'=>"sp_sales_order+1");
				$rs4 = $sp->update_data($update2,"sp_id='".$row['order_spid2']."'");
				$sp_money_data = array(
					  'log_spid' => $row['order_spid2'],
					  'log_sp' => $row['order_sp2'],
					  'log_type' => 'order_rebate',
					  'log_money' => $row['order_sp_rebate2'],
					  'log_content' => "交易返利(SN:".$row['order_sn'].")",
					  'log_create_time' => date("Y-m-d H:i:s"),
					  'log_main_id' => $row['order_id'],
				);
				$rs5 = $this->db->insert('data_sp_money_log', $sp_money_data); //商家资金记录	
			}else{
				$rs4 = '1';
				$rs5 = '1';
			}			
			if($rs1 && $rs2 && $rs3 && $rs4 && $rs5){
				$this->db->commit();
				return '1';
			}else{
				$this->db->back();	
				return '2';	
			}
			
		}else{
			return false;
			
		}
		
	}
	
	//获取快递的信息
	function get_express($company,$number){	
		$url = "http://api.kuaidi100.com/api?id=024fc3a51332b7a5&com=".$company."&nu=".$number."&valicode=&show=2&muti=1&order=desc";
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		return $output;
	}
	
	//提醒蔡鹏的邮件
	function send_controller_mail($sn){
		$row = $this->get_row_by_sn($sn);
		if(!$row){
			return false;
		}
		$row['order_detail'] = unserialize(stripslashes($row['order_detail']));	
		//dump($row['order_detail']);
		require(INC_PATH.'send_mail.php');
		require(CONFIG_PATH.'message_var.php');						
		$mail_to = '286837750@qq.com';
		$title_to =  '第二自然新订单提醒';
		$content_to = '<div style="width:660px;margin:0 auto;padding:20px;background-color:#f4f4f4;font-size:14px;color:#4d4d4d;line-height:1.5;margin-bottom:30px;">';
		$content_to .= '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
		$content_to .= '<tbody>';
		$content_to .= '<tr><td align="right">订单号： </td><td>'.$row['order_sn'].'</td></tr>';
		$content_to .= '<tr><td align="right">商品名称： </td><td>';
		foreach($row['order_detail'] as $v){
			foreach($v as $v2){
				$content_to .= $v2['item_name'].'<br>';	
			}
		}
		$content_to .= '</td></tr>';
		$content_to .= '<tr><td align="right">买家： </td><td>'.$row['order_name'].'</td></tr>';
		$content_to .= '<tr><td align="right">交易状态： </td><td>交易成功</td></tr>';
		$content_to .= '<tr><td align="right">数量： </td><td>'.$row['order_total_count'].'</td></tr>';
		$content_to .= '<tr><td align="right">订单总额： </td><td>'.$row['order_all_total'].'</td></tr>';
		$content_to .= '<tr><td align="right"></td><td></td></tr>';
		$content_to .= '<tr><td align="right"></td><td><strong style="display:block;margin-bottom:20px;font-size:14px;"><a href="http://www.d2ziran.com/admin/order-act_detail_id_'.$row['order_id'].'.htm?dpt=7" style="color:#f60;text-decoration:underline;" target="_blank">查看明细</a></strong></td></tr>';					
       	$content_to .= '</tbody></table></div>';
		
		$name_to = '蔡鹏';
		$mail_from =  $cf_mail_var['mail_from'];
		$mail_from_name = $cf_mail_var['mail_from_name'];			
		$result = send_mail($mail_to, $title_to, $content_to,$name_to,$mail_from,$mail_from_name);
		if($result){
			return true;
		}else{
			return false;
		}
	}
	 
	 
	 public function get_wxpay_url($info){
		require_once LIB_PATH."wxpay/WxPay.Api.php";
		require_once LIB_PATH."wxpay/WxPay.NativePay.php"; 
		$notify = new NativePay();
		$input = new WxPayUnifiedOrder();
		$input->SetBody($info['title']);
		$input->SetAttach($info['title']);
		$input->SetOut_trade_no($info['sn']);
		$input->SetTotal_fee($info['money']*100);
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag("第二自然商品");
		$input->SetNotify_url(SITE_ADDR."default/wxnotify.htm");
		$input->SetTrade_type("NATIVE");
		$input->SetProduct_id("1234567844");
		$result = $notify->GetPayUrl($input);			
		return $result["code_url"];		
	 }

	 //更新商品的购买
	 public function update_goods_user($order){	 	
	 	$sql = "SELECT user_headimg FROM data_user WHERE user_id = '".$order['order_uid']."' ";
	 	$user_headimg = $this->db->getOne($sql);
	 	$order_detail = unserialize($order['order_detail']);
	 	$insert_data['gbl_oid'] = $order['order_id'];
	 	$insert_data['gbl_uid'] = $order['order_uid'];
	 	$insert_data['gbl_username'] = $order['order_user'];
	 	$insert_data['gbl_userheadimg'] = $user_headimg;
	 	foreach ($order_detail as $v) {
	 		foreach ($v as $v2){
	 			$insert_data['gbl_gid']	= $v2['goods_id'];
	 			$insert_data['gbl_gname']= $v2['goods_name'];	 			
	 			$this->insert_goods_by_log($insert_data);
	 		}	 	
	 	}
	 }

	 public function insert_goods_by_log($data){
	 	$data['gbl_create_time'] = date("Y-m-d H:i:s");
	 	$table = 'data_goods_buy_log';
	 	$result = $this->db->insert($table,$data);
	 	return $result;
	 }
	
}

?>